package com.spark.trouble.agency

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import com.spark.trouble.R
import com.spark.trouble.SpotHanAgencyInfoModel
import kotlinx.android.synthetic.main.frag_goven_scheme.*

/**
 * [待办] -> 现场治理 -> 治理方案 -> 待审核
 */
class GovernSchemeFragment : BaseFragment() {
    private var taskId = ""

    companion object {
        fun newInstance(taskId: String): GovernSchemeFragment {
            val target = GovernSchemeFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_goven_scheme
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@GovernSchemeFragment.taskId = this
                fetchInfo(this)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank()) {
                                alert("请输入驳回理由")
                            } else {
                                d.dismiss()
                                submitAgencyRejctVerify(this@GovernSchemeFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitAgencyApproveVerify(taskId) }
    }

    /**
     * restore stateø
     */
    @SuppressLint("SetTextI18n")
    private fun restore(
            respMan: String,
            schemeContent: String,
            schemeFiles: MutableList<String>,
            acceptMan: String,
            acceptContent: String,
            acceptFiles: MutableList<String>
    ) {
        tv_resp_man.text = "责任人: $respMan"
        tv_scheme_content.text = schemeContent

        LogUtils.e("$schemeFiles")
        tv_scheme_sum.apply {
            val size = schemeFiles.size
            text = if (size == 0) "无附件" else "查看附件($size)"
            setOnClickListener {
                if (size == 0) return@setOnClickListener
                else {
                    gone(true)
                    recy_schemas.apply {
                        gone(false)
                        LogUtils.e("xxxxxxxxx")
                        layoutManager = LinearLayoutManager(context)
                        adapter = ImgAdapter(R.layout.item_rectify_upload_file).apply {
                            setOnItemChildClickListener { adapter, view, position ->
                                val file = schemeFiles[position]
                                when (view.id) {
                                    R.id.iv_glance -> toast("查看文件【${file}】")
                                    R.id.iv_delete -> remove(position)
                                }
                            }
                        }
                    }

                }
            }
        }
        tv_accept_man.text = acceptMan
        tv_accept_content.text = acceptContent
        LogUtils.e("$acceptFiles")
        tv_accept_sum.apply {
            val size = acceptFiles.size
            text = if (size == 0) "无附件" else "查看附件($size)"
            setOnClickListener {
                if (size == 0) return@setOnClickListener
                else {
                    gone(true)
                    recy_accets.apply {
                        gone(false)
                        layoutManager = LinearLayoutManager(context)
                        adapter = ImgAdapter(R.layout.item_rectify_upload_file).apply {
                            setOnItemChildClickListener { adapter, view, position ->
                                val file = acceptFiles[position]
                                when (view.id) {
                                    R.id.iv_glance -> toast("查看文件【${file}】")
                                    R.id.iv_delete -> remove(position)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        LogUtils.e("xaadadeadaew -> $taskId")
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_spot_fetch_verify}", mutableMapOf("taskId" to taskId))
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, SpotHanAgencyInfoModel::class.java)?.apply {
                                if (code == "200") {
                                    resultMaps[0].apply {
                                        restore(
                                                responsible_user_name,
                                                solution_content,
                                                solutionPICInfo.map { it.uri }.toMutableList(),
                                                acceptor_name,
                                                accept_reason,
                                                acceptionPICinfo.map { it.uri }.toMutableList()
                                        )
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }

    /**
     * [待办] 待审核 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyApproveVerify(taskId: String) {
        val params = mutableMapOf(
                "taskId" to taskId,
                "approveState" to "2"
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_spot_submit_verify}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }

    /**
     * [待办] -> 待审核 -> 驳回
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRejctVerify(taskId: String, rejectReason: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", mutableMapOf("taskId" to taskId, "refuseReason" to rejectReason).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }
}

class ImgAdapter(layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        if (item == null) return
        helper?.apply {
            val etFilename = getView<EditText>(R.id.tv_file_name).apply {
                setText(item)
                setOnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {
                        setSelection(string().length)
                    } else {
                        if (string().isNullOrBlank()) {
                            mContext.toast("请输入文件名")
                            setText(item)
                        } else {
                            //item = string()
                        }
                    }
                }
            }
            getView<ImageView>(R.id.iv_edit).setOnClickListener {
                val inputType = etFilename.inputType
                if (inputType != EditText.AUTOFILL_TYPE_NONE) etFilename.inputType = EditText.AUTOFILL_TYPE_NONE
                else etFilename.inputType = EditText.AUTOFILL_TYPE_TEXT
            }
            getView<ImageView>(R.id.iv_glance).setOnClickListener { onItemChildClickListener?.onItemChildClick(this@ImgAdapter, it, adapterPosition) }
            getView<ImageView>(R.id.iv_delete).setOnClickListener { onItemChildClickListener?.onItemChildClick(this@ImgAdapter, it, adapterPosition) }
        }
    }

}